package com.glowdayz.glowmee.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import com.glowdayz.common.DBHandler;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.PageHandler;
import com.glowdayz.glowmee.cmd.PouchCategoryCMD;

/** 파우치 카테고리의 기능을 구현하는 클래스 */
public class PouchCategoryDAO {
	
static Logger logger = Logger.getLogger(PouchCategoryDAO.class);
	
	private static PouchCategoryDAO instance = null;
	
	DBHandler db = null;
	
	public static PouchCategoryDAO getInstance() {
		if (instance == null) {
			instance = new PouchCategoryDAO();
		}
		return instance;
	}
	
	public PouchCategoryDAO() {
		db = DBHandler.getInstance();
	}
	
	/**
	 * 파우치 카테고리 전시여부
	 * @param cmd
	 * @return int
	 */
	public int unDisplayPouchCategory(PouchCategoryCMD cmd) throws SQLException {
		logger.debug("[unDisplayPouchCategory] ---------- Method Start ----------");
		logger.debug("[unDisplayPouchCategory][PARAM] PouchCategoryCMD cmd=" + cmd.toString());
		
		int result = 0;
		
		String sql = "UPDATE pouchcategory "
				+ "SET isDisplay=?, modified_date=? "
				+ "WHERE idPouchCategory=?";
		PreparedStatement pstmt = db.getPrepareStatement(sql);
		
		try {
			pstmt.setInt(1, cmd.getIsDisplay());
			pstmt.setString(2, DateTime.getInstance().getNowDateTimeString());
			pstmt.setInt(3, cmd.getIdPouchCategory());
			
			DBHandler.getInstance().beginTrans();
			result = pstmt.executeUpdate();
			
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[unDisplayPouchCategory] " + e.getLocalizedMessage());
			logger.error("[unDisplayPouchCategory] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[unDisplayPouchCategory][RETURN] result=" + result);
		logger.debug("[unDisplayPouchCategory] ---------- Method End ----------");
		
		return result;
	}
	
	/**
	 * 파우치 카테고리 추가
	 * @param cmd
	 * @return int
	 */
	public int insertPouchCategory(PouchCategoryCMD cmd) throws Exception {
		logger.debug("[insertPouchCategory] ---------- Method Start ----------");
		logger.debug("[insertPouchCategory][PARAM] PouchCategoryCMD cmd=" + cmd.toString());
		
		int result = 0;
		
		String sql = "INSERT INTO pouchcategory("
				+ "pouchCategoryText, sortKey, isDisplay, create_date"
				+ ") VALUES (?, ?, 1, ?);";
		PreparedStatement pstmt = db.getPrepareStatement(sql);
		
		try {
			pstmt.setString(1, cmd.getPouchCategoryText());
			pstmt.setInt(2, cmd.getSortKey());
			pstmt.setString(3, DateTime.getInstance().getNowDateTimeString());
			
			DBHandler.getInstance().beginTrans();
			int count = pstmt.executeUpdate();
			
			if (count > 0) {
				// 자동증가 일련변호 조회
				ResultSet rs = pstmt.getGeneratedKeys();
				if (rs.next()) {
					result = rs.getInt(1);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[insertPouchCategory] " + e.getLocalizedMessage());
			logger.error("[insertPouchCategory] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[insertPouchCategory][RETURN] result=" + result);
		logger.debug("[insertPouchCategory] ---------- Method End ----------");
		
		return result;
	}
	
	public int updatePouchCategory(PouchCategoryCMD cmd) throws SQLException {
		logger.debug("[updatePouchCategory] ---------- Method Start ----------");
		logger.debug("[updatePouchCategory][PARAM] PouchCategoryCMD cmd=" + cmd.toString());
		
		int result = 0;
		
		String sql = "UPDATE pouchcategory "
				+ "SET pouchCategoryText=?, sortKey=?, modified_date=? "
				+ "WHERE idPouchCategory=?";
		PreparedStatement pstmt = db.getPrepareStatement(sql);
		
		try {
			pstmt.setString(1, cmd.getPouchCategoryText());
			pstmt.setInt(2, cmd.getSortKey());
			pstmt.setString(3, DateTime.getInstance().getNowDateTimeString());
			pstmt.setInt(4, cmd.getIdPouchCategory());
			
			DBHandler.getInstance().beginTrans();
			result = pstmt.executeUpdate();
			
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[updatePouchCategory] " + e.getLocalizedMessage());
			logger.error("[updatePouchCategory] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[updatePouchCategory][RETURN] result=" + result);
		logger.debug("[updatePouchCategory] ---------- Method End ----------");
		
		return result;
	}
	
	public ArrayList<PouchCategoryCMD> getPouchCategoryList(int page, int count, String order) throws Exception {
		logger.debug("[getPouchCategoryList] ---------- Method Start ----------");
		logger.debug("[getPouchCategoryList][PARAM] page=" + page);
		logger.debug("[getPouchCategoryList][PARAM] count=" + count);
		logger.debug("[getPouchCategoryList][PARAM] order=" + order);
		
		ArrayList<PouchCategoryCMD> result = null;
		int cnt = db.getCount("pouchcategory", "idPouchCategory", null);
		
		if (count == -1) {
			count = cnt;
		}
		
		String sql = null;
		if (order == null || order.equals("")) {
			sql = "SELECT idPouchCategory id, pouchCategoryText, sortKey, isDisplay, create_date, modified_date, "
					+ "(SELECT COUNT(*) FROM pouch p WHERE p.idPouchCategory=id) count "
					+ "FROM pouchcategory "
					+ "LIMIT ?, ?";
		} else if (order != null) {
			sql = "SELECT idPouchCategory id, pouchCategoryText, sortKey, isDisplay, create_date, modified_date, "
					+ "(SELECT COUNT(*) FROM pouch p WHERE p.idPouchCategory=id) count "
					+ "FROM pouchcategory "
					+ "ORDER BY " + order + " "
					+ "LIMIT ?, ?";
		}
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(sql);
		
		if (cnt == 0) {
			PageHandler.getInstance(page, cnt);
		} else {
			// 페이징 처리 --> 한 페이지에 count개씩, 페이지번호는 10개 출력
			PageHandler.getInstance(page, cnt, count, 10);
		}
		
		try {
			pstmt.setInt(1, PageHandler.getInstance().getStartRec());
			pstmt.setInt(2, PageHandler.getInstance().getPageArticleCount());
			ResultSet rs = pstmt.executeQuery();
			
			if (rs != null) {
				
				// SQL문장에 이상이 없을 경우에만 list 객체를 할당한다.
				// 이 객체가 null이라면 SQL실행에 실패한 경우이다.
				// 객체가 생성되지만, add()가 실행되지 않아서, size()값이 0이라면
				// 조건에 맞는 데이터가 없는 경우이다.
				result = new ArrayList<PouchCategoryCMD>();
				
				while(rs.next()) {
					int num = rs.getInt(1);
					String pouchCategoryText = rs.getString(2);
					int sortKey = rs.getInt(3);
					int isDisplay = rs.getInt(4);
					String create_date = rs.getString(5);
					String modified_date = rs.getString(6);
					int pouchCnt = rs.getInt(7);
					PouchCategoryCMD item = new PouchCategoryCMD(num, pouchCategoryText, sortKey, isDisplay, create_date, modified_date, pouchCnt);
					result.add(item);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error("[getPouchCategoryList] " + e.getLocalizedMessage());
			logger.error("[getPouchCategoryList] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
			}
		}
		
		if (result != null) {
			logger.debug("[getPouchCategoryList][RETURN] result_count=" + result.size());
		}
		logger.debug("[getPouchCategoryList] ---------- Method End ----------");
		
		return result;
	}
	
	public ArrayList<String> getPouchCategoryXml() throws Exception {
		logger.debug("[getPouchCategoryXml] ---------- Method Start ----------");
		
		ArrayList<String> result = null;
		int cnt = db.getCount("pouchcategory", "idPouchCategory", "isDisplay=1");
		
		String sql = "SELECT pouchCategoryText "
				+ "FROM pouchcategory "
				+ "WHERE isDisplay=1 "
				+ "ORDER BY sortKey";
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(sql);
		
		PageHandler.getInstance(1, cnt);
		//PageHandler.getInstance(1, cnt, count, 10);
		
		try {
			ResultSet rs = pstmt.executeQuery();
			
			if (rs != null) {
				
				// SQL문장에 이상이 없을 경우에만 list 객체를 할당한다.
				// 이 객체가 null이라면 SQL실행에 실패한 경우이다.
				// 객체가 생성되지만, add()가 실행되지 않아서, size()값이 0이라면
				// 조건에 맞는 데이터가 없는 경우이다.
				result = new ArrayList<String>();
				
				while(rs.next()) {
					String pouchCategoryText = rs.getString(1);
					result.add(pouchCategoryText);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error("[getPouchCategoryXml] " + e.getLocalizedMessage());
			logger.error("[getPouchCategoryXml] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
			}
		}
		
		if (result != null) {
			logger.debug("[getPouchCategoryXml][RETURN] result_count=" + result.size());
		}
		logger.debug("[getPouchCategoryXml] ---------- Method End ----------");
		
		return result;
	}
	
}
